package com.edu.chat.web.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.edu.chat.web.common.RedisUtil;
import com.edu.chat.web.common.model.R;
import com.edu.chat.web.controller.vo.PageQuery;
import com.edu.chat.web.controller.vo.SessionVO;
import com.edu.chat.web.service.CsSessionService;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Set;

/**
 * @program: KQAIA
 * @description:
 * @author: 无恙
 * @create: 2025-03-30 17:10
 **/


@Slf4j
@RestController
@RequestMapping("/chat/session")
public class SessionController {

	@Autowired
	private CsSessionService csSessionService;

	@Autowired
	private RedisUtil redisUtil;

	/**
	 * 创建会话
	 * @param sessionVO
	 * @return
	 */
	@PostMapping("/create")
	public R<?> createSession(@RequestBody @Valid SessionVO sessionVO) {
		log.info("SessionController createSession 创建会话，参数：{}", sessionVO);
		return csSessionService.createSession(sessionVO);
	}

	/**
	 * 分页查询历史会话
	 * @param sessionVO
	 * @return
	 */
	@PostMapping("/query")
	public R<?> querySession(@RequestBody @Valid PageQuery<SessionVO> sessionVO) {
		log.info("SessionController querySession 分页查询历史会话，参数：{}", sessionVO);
		return R.success(csSessionService.listSession(sessionVO));
	}

	/*
	* @author 范铁凝
	* @date 2025/4/16
	* 修该会话名称
	*/
	@PostMapping("/update")
	public R<?> updateSessionName(String sessionId, String sessionName) {
		log.info("SessionController updateSessionName 修改会话名称{}，参数：{}", sessionId, sessionName);
		return csSessionService.updateSessionName(sessionId, sessionName);
	}

	/*
	* @author 范铁凝
	* @date 2025/4/20
	* 查询热门问题
	*/
	@GetMapping("/queryHot")
	public R<?> queryHot(@RequestParam("sceneId") String sceneId,@RequestParam("tenantId") String tenantId){

		//更新热门问题缓存
		Set<String> hotQuestion = redisUtil.rangeZset(sceneId, 0, 9);

		if(CollectionUtil.isNotEmpty(hotQuestion)){
			List<String> list = hotQuestion.stream().map(title -> title.split("##")[1]).filter(Objects::nonNull).toList();

			return R.success(list);

		}
		return R.fail("no data");

	}
}
